package com.hkbigdata.transfer;

import com.hkbigdata.bean.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;

/**
 * @author liuanbo
 * @creat 2024-04-12-17:28
 * @see 2194550857@qq.com
 */
public class Flink09_TransForm_Reduce_Anonymous {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20.0));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50.0));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50.0));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10.2));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30.2));

        KeyedStream<WaterSensor, String> waterSensorStringKeyedStream = env.fromCollection(waterSensors)
                .keyBy(WaterSensor::getId);

        //聚合
/*        SingleOutputStreamOperator<WaterSensor> reduce = waterSensorStringKeyedStream.reduce(new ReduceFunction<WaterSensor>() {
            @Override
            public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                return new WaterSensor(value1.getId(), value2.getTs(), value1.getVc() + value2.getVc());
            }
        });*/
        waterSensorStringKeyedStream.reduce((data1, data2) -> {
            return new WaterSensor(data1.getId(), data2.getTs(), data1.getVc() + data2.getVc());
        }).print();

//        reduce.print();
        env.execute();


    }
}
